<route lang="json5" type="page">
  {
    style: {
      navigationBarTitleText: '学习打卡',
    },
  }
</route>

<template>
  <view class="study-checkin-container">

    <!-- 功能图标区域 -->
    <view class="function-icons">
      <view class="icon-item" v-for="item in functionIcons" :key="item.id" @click="handleIconClick(item)">
        <view class="icon-wrapper" :style="{ backgroundColor: item.bgColor }">
          <text class="iconfont" :class="item.icon"></text>
        </view>
        <text class="icon-label">{{ item.label }}</text>
      </view>
    </view>

    <!-- 阅读统计和打卡区域 -->
    <view class="reading-checkin-section">
      <!-- 总阅读天数 -->
      <view class="total-reading">
        <text class="total-title">总阅读天数</text>
        <text class="total-days">{{ totalReadingDays }}天</text>
      </view>

      <!-- 阅读统计 -->
      <view class="reading-stats">
        <view class="stat-item">
          <text class="stat-label">今日阅读</text>
          <text class="stat-number">{{ todayReading }}</text>
          <text class="stat-unit">本</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">本周阅读</text>
          <text class="stat-number">{{ weekReading }}</text>
          <text class="stat-unit">本</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">本月阅读</text>
          <text class="stat-number">{{ monthReading }}</text>
          <text class="stat-unit">本</text>
        </view>
      </view>

      <!-- 今日阅读绘本展示 -->
      <view class="books-display" v-if="todayBooks.length > 0">
        <view class="books-grid">
          <view
            class="book-item"
            v-for="book in displayBooks"
            :key="book.id"
          >
            <image
              class="book-cover"
              :src="book.bookCover"
              mode="aspectFit"
              @error="onImageError"
            />
            <text class="book-title">{{ book.bookTitle }}</text>
          </view>

          <!-- 更多绘本提示 -->
          <view class="more-books" v-if="showMoreBooks" @click="showAllBooksModal">
            <view class="more-icon">
              <text class="more-text">+{{ todayBooks.length - 2 }}</text>
            </view>
            <text class="more-title">更多</text>
          </view>
        </view>
      </view>

      <!-- 打卡按钮 -->
      <view class="checkin-button">
        <view
          class="checkin-btn"
          :class="{ checked: todayChecked, disabled: isButtonDisabled }"
          @click="toggleCheckin"
        >
          <text class="checkin-text">{{ getButtonText() }}</text>
        </view>

      </view>
    </view>

    <!-- 打卡日历 -->
    <view class="calendar-section">
      <view class="calendar-header">
        <text class="calendar-title">打卡日历</text>
        <text class="calendar-nav" @click="openCalendar">更多 ></text>
      </view>

      <view class="recent-calendar">
        <view v-for="day in recentDays" :key="day.date" class="day-item">
          <text class="day-name">{{ day.name }}</text>
          <view class="day-circle" :class="{ checked: day.checked, today: day.isToday }">
            <text class="day-number">{{ day.day }}</text>
          </view>
          <text class="week-day">{{ day.weekDay }}</text>
        </view>
      </view>
    </view>

    <!-- 动态列表 -->
    <view class="activity-section">
      <view class="activity-tabs">
        <view class="tab-item" :class="{ active: activeTab === 'latest', loading: activityLoading && activeTab === 'latest' }" @click="switchTab('latest')">
          <text>最新</text>
          <view v-if="activityLoading && activeTab === 'latest'" class="tab-loading"></view>
        </view>
        <view class="tab-item" :class="{ active: activeTab === 'follow', loading: activityLoading && activeTab === 'follow' }" @click="switchTab('follow')">
          <text>关注</text>
          <view v-if="activityLoading && activeTab === 'follow'" class="tab-loading"></view>
        </view>
        <view class="tab-item" :class="{ active: activeTab === 'mine', loading: activityLoading && activeTab === 'mine' }" @click="switchTab('mine')">
          <text>我的</text>
          <view v-if="activityLoading && activeTab === 'mine'" class="tab-loading"></view>
        </view>
      </view>

      <!-- 动态列表加载状态 -->
      <view v-if="activityLoading" class="activity-loading">
        <view class="loading-item" v-for="i in 3" :key="i">
          <view class="loading-avatar"></view>
          <view class="loading-content">
            <view class="loading-line short"></view>
            <view class="loading-line long"></view>
            <view class="loading-line medium"></view>
          </view>
        </view>
      </view>

      <!-- 动态列表内容 -->
      <scroll-view
        v-else
        class="activity-scroll"
        scroll-y
        :enhanced="true"
        :show-scrollbar="false"
        @scrolltolower="loadMorePunchRecords"
      >
        <view class="activity-list">
          <view v-if="currentActivityList.length === 0" class="empty-state">
            <text class="empty-text">
              {{ activeTab === 'follow' ? '暂无关注用户的动态\n快去关注一些小伙伴吧~' : '暂无动态记录' }}
            </text>
          </view>
          <view v-else v-for="activity in currentActivityList" :key="activity.id" class="activity-item" @click="showActivityDetail(activity)">
            <view class="user-header">
              <view class="user-avatar">
                <!-- 优先显示用户头像图片 -->
                <image
                  v-if="activity.userInfo?.avatar && !activity.avatarLoadError"
                  :src="activity.userInfo.avatar"
                  class="avatar-image"
                  mode="aspectFill"
                  @error="handleAvatarError(activity)"
                />
                <!-- 头像加载失败或没有头像时显示文字头像 -->
                <text v-else class="avatar-text" :style="{ backgroundColor: activity.avatarBg }">{{ activity.avatarText }}</text>
              </view>
              <view class="user-info">
                <view class="user-name-row">
                  <text class="username">{{ activity.username }}</text>
                  <text class="time-desc">{{ activity.timeDesc }}</text>
                  <view class="follow-btn" v-if="activeTab !== 'mine' && shouldShowFollowButton(activity)" @click.stop="toggleFollow(activity)">
                    <text class="follow-text">{{ activity.isFollowed ? '已关注' : '+ 关注' }}</text>
                  </view>
                </view>
                <text class="checkin-desc">{{ activity.checkinDesc }}</text>
              </view>
            </view>

            <view class="reading-content">
              <text class="reading-title">{{ activity.readingTitle }}</text>
              <text class="reading-count">{{ activity.readingCount }}</text>

              <!-- 用户心得 -->
              <view class="comment-content" v-if="activity.commentText">
                <text class="comment-text">{{ activity.commentText }}</text>
              </view>

              <view class="book-list" v-if="activity.books && activity.books.length > 0">
                <view v-for="book in activity.books" :key="book.id" class="book-item">
                  <image class="book-cover" :src="book.cover" mode="aspectFill" />
                  <text class="book-title">{{ book.title }}</text>
                </view>
              </view>
            </view>
          </view>

          <!-- 加载更多指示器 -->
          <view v-if="getCurrentPaginationState().loading" class="load-more-indicator">
            <view class="loading-spinner"></view>
            <text class="loading-text">加载中...</text>
          </view>

          <!-- 没有更多数据提示 -->
          <view v-else-if="!getCurrentPaginationState().hasMore && currentActivityList.length > 0" class="no-more-indicator">
            <text class="no-more-text">没有更多数据了</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 动态详情弹窗 -->
    <view v-if="showDetailModal" class="detail-modal-overlay" @click="hideActivityDetail">
      <view class="detail-modal-content" @click.stop>
        <!-- 关闭按钮 -->
        <view class="modal-close-btn" @click="hideActivityDetail">
          <wd-icon name="close" size="22px"></wd-icon>
        </view>

        <!-- 滚动容器 -->
        <scroll-view class="modal-scroll-container" :scroll-y="true" :enhanced="true" :show-scrollbar="false">
          <!-- 用户信息 -->
          <view class="modal-user-header">
          <view class="modal-user-avatar">
            <!-- 优先显示用户头像图片 -->
            <image
              v-if="selectedActivity?.userInfo?.avatar && !selectedActivity?.avatarLoadError"
              :src="selectedActivity.userInfo.avatar"
              class="avatar-image"
              mode="aspectFill"
              @error="handleModalAvatarError"
            />
            <!-- 头像加载失败或没有头像时显示文字头像 -->
            <text v-else class="avatar-text" :style="{ backgroundColor: selectedActivity?.avatarBg }">
              {{ selectedActivity?.avatarText }}
            </text>
          </view>
          <view class="modal-user-info">
            <text class="modal-username">{{ selectedActivity?.username }}</text>
            <text class="modal-time">{{ formatFullTime(selectedActivity?.fullTime) }}</text>
            <text class="modal-day-count">打卡第{{ selectedActivity?.dayCount }}天</text>
          </view>
          <!-- 关注按钮 -->
          <view v-if="shouldShowFollowButton(selectedActivity)" class="modal-header-follow-btn" @click.stop="toggleFollow(selectedActivity)">
            <text class="header-follow-text">{{ selectedActivity?.isFollowed ? '已关注' : '+ 关注' }}</text>
          </view>
        </view>

        <!-- 分割线 -->
        <view class="modal-divider"></view>

        <!-- 阅读统计 -->
        <view class="modal-reading-stats">
          <view class="stats-header">
            <text class="stats-icon">📖</text>
            <text class="stats-title">今日阅读</text>
          </view>
          <text class="stats-content">
            读了{{ selectedActivity?.fullBooks?.length || 0 }}本绘本{{ selectedActivity?.readingTime > 0 ? `，共计${formatReadingTime(selectedActivity.readingTime)}` : '' }}
          </text>
        </view>

        <!-- 阅读心得 -->
        <view v-if="selectedActivity?.commentText" class="modal-comment-section">
          <view class="comment-header">
            <text class="comment-icon">💭</text>
            <text class="comment-title">阅读心得</text>
          </view>
          <text class="modal-comment-text">{{ selectedActivity.commentText }}</text>
        </view>

        <!-- 阅读的绘本 -->
        <view v-if="selectedActivity?.fullBooks?.length > 0" class="modal-books-section">
          <view class="books-header">
            <text class="books-icon">📚</text>
            <text class="books-title">阅读的绘本</text>
          </view>
          <view class="modal-books-grid">
            <view v-for="book in selectedActivity.fullBooks" :key="book.id" class="modal-book-item">
              <image class="modal-book-cover" :src="book.cover" mode="aspectFill" />
              <text class="modal-book-title">{{ book.title }}</text>
              <text v-if="book.bookSetTitle" class="modal-book-set">{{ book.bookSetTitle }}</text>
            </view>
          </view>
        </view>
        </scroll-view>
      </view>
    </view>

    <!-- 今日绘本展示弹窗 -->
    <view v-if="showAllBooksModalVisible" class="detail-modal-overlay" @click="hideAllBooksModal">
      <view class="detail-modal-content" @click.stop>
        <!-- 关闭按钮 -->
        <view class="modal-close-btn" @click="hideAllBooksModal">
          <wd-icon name="close" size="22px"></wd-icon>
        </view>

        <!-- 滚动容器 -->
        <scroll-view class="modal-scroll-container" :scroll-y="true" :enhanced="true" :show-scrollbar="false">
          <!-- 标题 -->
          <view class="modal-books-header">
            <view class="books-header">
              <text class="books-icon">📚</text>
              <text class="books-title">今日阅读绘本</text>
            </view>
            <text class="books-count">共{{ todayBooks.length }}本</text>
          </view>

          <!-- 分割线 -->
          <view class="modal-divider"></view>

          <!-- 绘本网格 -->
          <view class="modal-books-section">
            <view class="modal-books-grid">
              <view v-for="book in todayBooks" :key="book.id" class="modal-book-item">
                <image class="modal-book-cover" :src="book.bookCover" mode="aspectFill" @error="onImageError" />
                <text class="modal-book-title">{{ book.bookTitle }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import {
  getPunchStats,
  getPunchList,
  getPunchListPage,
  canPunchToday,
  getTodayPunch,
  getPunchCalendar,
  getPublicPunchRecords,
  getPublicPunchRecordsPage
} from '@/api/punch'
import {
  getTodayReadingRecords
} from '@/api/reading-records'
import {
  getUserProfile
} from '@/api/profile'
import {
  followUser,
  unfollowUser,
  getFollowingList
} from '@/api/userActions'
import type {
  PunchStatsRespVO,
  PunchRecordRespVO,
  PunchDayVO
} from '@/api/types/punch'
import type { ReadingHistoryRespVO } from '@/types/reading-records'

// 功能图标数据
const functionIcons = ref([
  {
    id: 1,
    label: '启蒙方法',
    icon: 'icon-shiyongshouce',
    bgColor: '#6c5ce7'
  },
  {
    id: 2,
    label: '我的配音',
    icon: 'icon-yonghu',
    bgColor: '#fd79a8'
  },
  {
    id: 3,
    label: '磨耳朵',
    icon: 'icon-kefu',
    bgColor: '#00b894'
  },
])

// 绘本数据接口已使用ReadingHistoryRespVO替代

// 加载状态
const loading = ref(false)
const statsLoading = ref(false)
const activityLoading = ref(false)

// 阅读统计数据
const punchStats = ref<PunchStatsRespVO | null>(null)
const totalReadingDays = computed(() => punchStats.value?.totalPunchDays || 0)
const todayReading = computed(() => todayBooks.value.length)
const weekReading = computed(() => {
  const weekStats = punchStats.value?.weeklyStats?.[0]
  return weekStats?.bookCount || 0
})
const monthReading = computed(() => {
  const monthStats = punchStats.value?.monthlyStats?.[0]
  return monthStats?.bookCount || 0
})

// 今日阅读的绘本列表
const todayBooks = ref<ReadingHistoryRespVO[]>([])

// 打卡状态
const todayChecked = ref(false)
const canPunchTodayStatus = ref(false)

// 按钮禁用状态
const isButtonDisabled = computed(() => {
  return todayBooks.value.length === 0
})

// 获取按钮文本
const getButtonText = () => {
  if (todayBooks.value.length === 0) {
    return '请先阅读绘本'
  }
  return todayChecked.value ? `今日已读${todayBooks.value.length}本，重新打卡` : `今日读了${todayBooks.value.length}本，打个卡`
}



// 打卡记录列表
const punchRecords = ref<PunchRecordRespVO[]>([])

// 当前登录用户信息
const currentUser = ref<{ id: number; username: string } | null>(null)

// 关注的用户列表
const followingUserIds = ref<Set<number>>(new Set())

// 最近6天打卡数据 - 从API获取
const recentDays = ref([])

// 动态详情弹窗相关
const showDetailModal = ref(false)
const selectedActivity = ref<any>(null)

// 今日绘本展示弹窗相关
const showAllBooksModalVisible = ref(false)

// 头像加载错误处理
function handleAvatarError(activity: any) {
  console.log('头像加载失败，切换到文字头像:', activity.username)
  activity.avatarLoadError = true
}

// 弹窗头像加载错误处理
function handleModalAvatarError() {
  console.log('弹窗头像加载失败，切换到文字头像')
  if (selectedActivity.value) {
    selectedActivity.value.avatarLoadError = true
  }
}

// 生成最近6天打卡数据
const generateRecentDays = async () => {
  try {
    const today = new Date()

    // 计算最近6天的日期（包括今天）
    const recentDates = []
    for (let i = 5; i >= 0; i--) {
      const date = new Date(today)
      date.setDate(today.getDate() - i)
      recentDates.push(date)
    }

    // 确定需要获取的月份数据
    const monthsToFetch = new Set<string>()
    recentDates.forEach(date => {
      const yearMonth = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}`
      monthsToFetch.add(yearMonth)
    })

    // 获取所需月份的打卡数据
    const allPunchDays = []
    for (const yearMonth of Array.from(monthsToFetch)) {
      try {
        const response = await getPunchCalendar({ yearMonth })
        if (response.code === 0 && response.data?.punchDays) {
          allPunchDays.push(...response.data.punchDays)
        }
      } catch (error) {
        console.error(`获取${yearMonth}打卡数据失败:`, error)
      }
    }

    // 生成最近6天的显示数据
    const recentData = []
    const todayStr = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`

    for (const date of recentDates) {
      const dateStr = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
      const isToday = dateStr === todayStr

      // 查找该日期的打卡记录
      const punchRecord = allPunchDays.find((day: PunchDayVO) => {
        if (!day.date) return false

        let recordDateStr = ''
        if (Array.isArray(day.date)) {
          // 后端返回数组格式 [年, 月, 日]
          const [year, month, dayNum] = day.date
          recordDateStr = `${year}-${month.toString().padStart(2, '0')}-${dayNum.toString().padStart(2, '0')}`
        } else if (typeof day.date === 'string') {
          // 字符串格式
          recordDateStr = day.date
        } else {
          // 其他格式转换为字符串
          recordDateStr = String(day.date)
        }

        return recordDateStr === dateStr
      })

      // 生成显示的日期格式（月/日）和周几
      const displayDate = `${date.getMonth() + 1}/${date.getDate()}`
      const weekDayNames = ['日', '一', '二', '三', '四', '五', '六']
      const weekDay = weekDayNames[date.getDay()]

      recentData.push({
        name: displayDate,
        weekDay: weekDay,
        day: date.getDate(),
        date: dateStr,
        checked: !!punchRecord?.isPunched,
        isToday
      })
    }

    recentDays.value = recentData
  } catch (error) {
    console.error('生成最近6天打卡数据失败:', error)
    // 如果API失败，生成空的最近6天数据
    const today = new Date()
    const todayStr = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`

    const recentData = []
    const weekDayNames = ['日', '一', '二', '三', '四', '五', '六']
    for (let i = 5; i >= 0; i--) {
      const date = new Date(today)
      date.setDate(today.getDate() - i)

      const dateStr = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
      const isToday = dateStr === todayStr
      const displayDate = `${date.getMonth() + 1}/${date.getDate()}`
      const weekDay = weekDayNames[date.getDay()]

      recentData.push({
        name: displayDate,
        weekDay: weekDay,
        day: date.getDate(),
        date: dateStr,
        checked: false,
        isToday
      })
    }

    recentDays.value = recentData
  }
}

// 显示的绘本逻辑
const displayBooks = computed(() => {
  if (todayBooks.value.length <= 3) {
    // 3本或以下，显示全部
    return todayBooks.value
  } else {
    // 超过3本，只显示前2本
    return todayBooks.value.slice(0, 2)
  }
})

// 是否显示更多按钮
const showMoreBooks = computed(() => {
  return todayBooks.value.length > 3
})

// 活动tab
const activeTab = ref('mine')

// 最新动态数据 - 从API获取
const latestActivityList = ref([])

// 关注动态数据 - 从API获取
const followActivityList = ref([])

// 我的动态数据 - 从API获取
const myActivityList = ref([])

// 原始打卡记录数据存储（按tab分类）
const rawPunchRecords = ref({
  mine: [] as PunchRecordRespVO[],
  latest: [] as PunchRecordRespVO[],
  follow: [] as PunchRecordRespVO[]
})

// 分页状态管理
const paginationState = ref({
  mine: { currentPage: 1, hasMore: true, loading: false },
  latest: { currentPage: 1, hasMore: true, loading: false },
  follow: { currentPage: 1, hasMore: true, loading: false }
})

// 当前显示的动态列表
const currentActivityList = computed(() => {
  switch (activeTab.value) {
    case 'latest':
      return latestActivityList.value
    case 'follow':
      return followActivityList.value
    case 'mine':
      return myActivityList.value
    default:
      return myActivityList.value
  }
})

// 获取当前tab的分页状态
const getCurrentPaginationState = () => {
  return paginationState.value[activeTab.value as keyof typeof paginationState.value]
}

// 获取指定tab的活动列表
const getCurrentActivityList = (tab: string) => {
  switch (tab) {
    case 'latest':
      return latestActivityList.value
    case 'follow':
      return followActivityList.value
    case 'mine':
      return myActivityList.value
    default:
      return []
  }
}

// 功能图标点击
const handleIconClick = (item: any) => {
  switch (item.id) {
    case 1: // 启蒙方法
      uni.showToast({
        title: '启蒙方法功能开发中',
        icon: 'none'
      })
      break
    case 2: // 我的配音
      uni.navigateTo({
        url: '/pages-sub/profile/my-dubbing/index'
      })
      break
    case 3: // 磨耳朵
      uni.navigateTo({
        url: '/pages/audio/index'
      })
      break
    default:
      uni.showToast({
        title: `点击了${item.label}`,
        icon: 'none'
      })
  }
}

// 打开日历页面
const openCalendar = () => {
  uni.navigateTo({
    url: '/pages/checkin-calendar/index'
  })
}

// 切换打卡状态
const toggleCheckin = async () => {
  // 如果按钮被禁用，不执行任何操作
  if (isButtonDisabled.value) {
    uni.showToast({
      title: '请先阅读绘本再打卡',
      icon: 'none'
    })
    return
  }

  if (!todayChecked.value) {
    // 首次打卡，跳转到打卡页面
    uni.navigateTo({
      url: `/pages/checkin/index?bookCount=${todayReading.value}`
    })
  } else {
    // 已打卡，支持重新打卡
    try {
      // 获取今日打卡记录详情
      const todayPunchResponse = await getTodayPunch()
      if (todayPunchResponse.code === 0 && todayPunchResponse.data) {
        const punchRecord = todayPunchResponse.data
        // 跳转到重新打卡页面，传递现有打卡记录信息
        uni.navigateTo({
          url: `/pages/checkin/index?bookCount=${todayReading.value}&isRepunch=true&punchId=${punchRecord.id}&existingContent=${encodeURIComponent(punchRecord.commentText || '')}`
        })
      } else {
        // 如果获取不到打卡记录，按首次打卡处理
        uni.navigateTo({
          url: `/pages/checkin/index?bookCount=${todayReading.value}`
        })
      }
    } catch (error) {
      console.error('获取今日打卡记录失败:', error)
      uni.showToast({
        title: '获取打卡信息失败',
        icon: 'none'
      })
    }
  }
}

// 图片加载错误处理
function onImageError() {
  // 可以设置默认图片
}

// 切换活动tab
const switchTab = async (tab: string) => {
  // 如果正在加载或者点击的是当前tab，直接返回
  if (activityLoading.value || activeTab.value === tab) {
    return
  }

  // 开始加载
  activityLoading.value = true

  try {
    // 重置目标tab的分页状态
    const targetState = paginationState.value[tab as keyof typeof paginationState.value]
    targetState.currentPage = 1
    targetState.hasMore = true
    targetState.loading = false

    // 重置原始数据
    rawPunchRecords.value[tab as keyof typeof rawPunchRecords.value] = []

    // 如果切换到关注动态，先确保关注列表是最新的
    if (tab === 'follow') {
      await loadFollowingList()
    }

    // 加载动态数据
    await loadPunchRecords(tab)

    // 数据加载完成后再切换显示
    activeTab.value = tab
  } catch (error) {
    console.error('切换tab失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
  } finally {
    // 确保加载状态被重置
    activityLoading.value = false
    console.log('[switchTab] 加载状态重置，activityLoading:', activityLoading.value)
  }
}

// 获取当前用户信息
const loadCurrentUser = async () => {
  try {
    const response = await getUserProfile()

    if (response.code === 0 && response.data) {
      currentUser.value = {
        id: response.data.id,
        username: response.data.username || `user_${response.data.id}`
      }
    } else {
      // 如果是401未登录错误，跳转到登录页面
      if (response.code === 401) {
        handleUserNotLoggedIn()
        return
      }
      // 其他错误，尝试从本地存储获取用户信息作为fallback
      await loadUserFromLocalStorage()
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 检查是否是认证错误
    if (error.message && error.message.includes('账号未登录')) {
      handleUserNotLoggedIn()
      return
    }
    // 其他错误，尝试从本地存储获取用户信息作为fallback
    await loadUserFromLocalStorage()
  }
}

// 处理用户未登录的情况
const handleUserNotLoggedIn = () => {
  uni.showToast({
    title: '请先登录',
    icon: 'none'
  })

  // 跳转到登录页面
  setTimeout(() => {
    uni.reLaunch({
      url: '/pages/login/index'
    })
  }, 1500)
}

// 从本地存储加载用户信息作为fallback
const loadUserFromLocalStorage = async () => {
  try {
    const userInfo = uni.getStorageSync('userInfo')
    const token = uni.getStorageSync('token')

    if (userInfo && userInfo.id && token) {
      currentUser.value = {
        id: parseInt(userInfo.id),
        username: userInfo.username || userInfo.nickname || `user_${userInfo.id}`
      }
    } else {
      // 如果本地也没有有效的登录信息，跳转到登录页面
      handleUserNotLoggedIn()
    }
  } catch (error) {
    console.error('从本地存储加载用户信息失败:', error)
    // 如果出错，跳转到登录页面
    handleUserNotLoggedIn()
  }
}

// 加载关注列表
const loadFollowingList = async () => {
  try {
    const response = await getFollowingList(1000)
    if (response.code === 0 && response.data) {
      // 后端返回的是FollowUserRespVO数组，userId字段包含被关注用户的ID
      const userIds = response.data.map((user: any) => user.userId)
      followingUserIds.value = new Set(userIds)
      console.log('关注列表加载成功，关注用户数:', userIds.length)
    }
  } catch (error) {
    console.error('获取关注列表失败:', error)
  }
}

// 判断是否显示关注按钮
const shouldShowFollowButton = (activity: any) => {
  if (!currentUser.value) {
    return false
  }

  // 获取动态发布者的用户ID - 只从userInfo中获取，不使用activity.id（那是打卡记录ID）
  const activityUserId = activity.userInfo?.userId || activity.userId

  // 如果没有有效的用户ID，不显示关注按钮
  if (!activityUserId) {
    return false
  }

  // 如果是当前用户自己的动态，不显示关注按钮
  return activityUserId !== currentUser.value.id
}

// 更新所有动态列表中指定用户的关注状态
const updateFollowStatusInAllLists = (userId: number, isFollowed: boolean) => {
  // 更新最新动态列表
  latestActivityList.value.forEach(activity => {
    const activityUserId = activity.userInfo?.userId || activity.userId
    if (activityUserId === userId) {
      activity.isFollowed = isFollowed
    }
  })

  // 更新关注动态列表
  followActivityList.value.forEach(activity => {
    const activityUserId = activity.userInfo?.userId || activity.userId
    if (activityUserId === userId) {
      activity.isFollowed = isFollowed
    }
  })

  // 更新我的动态列表（虽然不会显示关注按钮，但保持数据一致性）
  myActivityList.value.forEach(activity => {
    const activityUserId = activity.userInfo?.userId || activity.userId
    if (activityUserId === userId) {
      activity.isFollowed = isFollowed
    }
  })
}

// 切换关注状态
const toggleFollow = async (activity: any) => {
  try {
    const userId = activity.userInfo?.userId || activity.userId

    // 如果没有有效的用户ID，不能进行关注操作
    if (!userId) {
      uni.showToast({
        title: '用户信息错误',
        icon: 'none'
      })
      return
    }

    // 检查是否是自己
    if (currentUser.value && userId === currentUser.value.id) {
      uni.showToast({
        title: '不能关注自己',
        icon: 'none'
      })
      return
    }

    if (activity.isFollowed) {
      // 取消关注前确认
      const result = await uni.showModal({
        title: '确认取消关注',
        content: `确定要取消关注 ${activity.userInfo?.nickname || activity.userInfo?.username || '该用户'} 吗？`,
        confirmText: '确定',
        cancelText: '取消'
      })

      if (!result.confirm) {
        return
      }

      console.log('准备取消关注用户:', userId)
      console.log('unfollowUser 函数:', typeof unfollowUser)
      await unfollowUser(userId)
      activity.isFollowed = false

      // 从关注列表中移除该用户
      followingUserIds.value.delete(userId)

      // 更新所有动态列表中该用户的关注状态
      updateFollowStatusInAllLists(userId, false)

      // 如果当前在关注动态页面，需要重新加载数据
      if (activeTab.value === 'follow') {
        await loadPunchRecords('follow')
      }

      uni.showToast({
        title: '取消关注成功',
        icon: 'none'
      })
    } else {
      console.log('准备关注用户:', userId)
      console.log('followUser 函数:', typeof followUser)
      await followUser(userId)
      activity.isFollowed = true

      // 添加到关注列表
      followingUserIds.value.add(userId)

      // 更新所有动态列表中该用户的关注状态
      updateFollowStatusInAllLists(userId, true)

      uni.showToast({
        title: '关注成功',
        icon: 'none'
      })
    }
  } catch (error: any) {
    console.error('关注操作失败:', error)

    // 处理特定错误码
    let errorMessage = '操作失败，请重试'
    if (error?.data?.code === 1100013002) {
      errorMessage = '不能关注自己'
    } else if (error?.data?.code === 1100013001) {
      errorMessage = '已关注该用户'
    } else if (error?.data?.code === 1100013000) {
      errorMessage = '关注关系不存在'
    }

    uni.showToast({
      title: errorMessage,
      icon: 'none'
    })
  }
}

// API调用函数
const loadPunchStats = async () => {
  try {
    statsLoading.value = true
    const response = await getPunchStats()
    if (response.code === 0) {
      punchStats.value = response.data
    }
  } catch (error) {
    console.error('获取打卡统计失败:', error)
    uni.showToast({
      title: '获取统计数据失败',
      icon: 'none'
    })
  } finally {
    statsLoading.value = false
  }
}

const loadTodayReading = async () => {
  try {
    const response = await getTodayReadingRecords()

    // 检查不同的响应格式
    let todayData
    if (response.data && response.data.code === 0) {
      // 格式1: {data: {code: 0, data: {readBookCount: 4, bookList: [...]}}}
      todayData = response.data.data
    } else if (response.data && response.data.readBookCount !== undefined) {
      // 格式2: {data: {readBookCount: 4, bookList: [...]}}
      todayData = response.data
    } else if (response.readBookCount !== undefined) {
      // 格式3: {readBookCount: 4, bookList: [...]}
      todayData = response
    } else {
      todayBooks.value = []
      return
    }

    const bookList = todayData?.bookList || []

    // 转换数据格式以匹配ReadingHistoryRespVO
    todayBooks.value = bookList.map((book: any) => {
      // 处理时间格式：如果是时间戳则转换为ISO字符串
      let readAtStr = book.readAt
      if (typeof book.readAt === 'number') {
        readAtStr = new Date(book.readAt).toISOString()
      }

      return {
        id: book.id,
        bookId: book.id,
        bookTitle: book.title,
        bookCover: book.cover,
        isCompleted: book.isCompleted,
        readingProgress: book.readingProgress,
        readingTime: 0,
        lastReadAt: readAtStr,
        completedAt: book.isCompleted ? readAtStr : undefined
      }
    })
  } catch (error) {
    console.error('获取今日阅读记录失败:', error)
    todayBooks.value = []
  }
}



const loadPunchRecords = async (tab: string = 'mine', isLoadMore: boolean = false) => {
  try {
    const state = paginationState.value[tab as keyof typeof paginationState.value]

    // 如果是加载更多但没有更多数据，直接返回
    if (isLoadMore && !state.hasMore) {
      return
    }

    // 如果正在加载，避免重复请求
    if (state.loading) {
      return
    }

    state.loading = true

    let response: any
    const page = isLoadMore ? state.currentPage + 1 : 1
    const limit = 10 // 每页10条数据

    if (tab === 'mine') {
      // 获取当前用户的打卡记录
      response = await getPunchListPage({ page, limit })
    } else {
      // 获取公开的打卡动态
      response = await getPublicPunchRecordsPage({ page, limit })
    }

    if (response.code === 0) {
      let records = response.data?.list || []
      const total = response.data?.total || 0

      console.log(`[${tab}] 获取到打卡记录:`, records.length, '条，总数:', total)
      console.log(`[${tab}] 原始数据:`, records)

      // 如果是关注动态，只显示已关注用户的动态
      if (tab === 'follow') {
        records = records.filter((record: any) => {
          const userId = record.userInfo?.userId || record.userId
          return userId && followingUserIds.value.has(userId)
        })
        console.log(`[${tab}] 过滤后记录:`, records.length, '条')
      }

      if (isLoadMore) {
        // 加载更多：追加原始数据
        const currentRecords = rawPunchRecords.value[tab as keyof typeof rawPunchRecords.value] || []
        const allRecords = [...currentRecords, ...records]
        console.log(`[${tab}] 加载更多 - 当前记录:`, currentRecords.length, '新记录:', records.length, '合并后:', allRecords.length)
        rawPunchRecords.value[tab as keyof typeof rawPunchRecords.value] = allRecords
        updateActivityList(tab, allRecords)
        state.currentPage = page
      } else {
        // 首次加载或刷新：替换数据
        rawPunchRecords.value[tab as keyof typeof rawPunchRecords.value] = records
        punchRecords.value = records // 保持兼容性
        updateActivityList(tab, records)
        state.currentPage = 1
      }

      // 判断是否还有更多数据
      const currentTotal = getCurrentActivityList(tab).length
      state.hasMore = currentTotal < total

      console.log(`[${tab}] 更新后活动列表长度:`, currentTotal, '是否还有更多:', state.hasMore)
    }
  } catch (error) {
    console.error('获取打卡记录失败:', error)
    throw error // 重新抛出错误，让switchTab处理
  } finally {
    const state = paginationState.value[tab as keyof typeof paginationState.value]
    state.loading = false
  }
}

// 加载更多打卡记录
const loadMorePunchRecords = async () => {
  console.log('[loadMorePunchRecords] 触发加载更多，当前tab:', activeTab.value)
  await loadPunchRecords(activeTab.value, true)
}

const checkTodayPunchStatus = async () => {
  try {
    const [canPunchResponse, todayPunchResponse] = await Promise.all([
      canPunchToday(),
      getTodayPunch()
    ])

    if (canPunchResponse.code === 0) {
      canPunchTodayStatus.value = canPunchResponse.data
    }

    // 后端返回的是PunchRecordRespVO或null，不是TodayPunchRespVO
    if (todayPunchResponse.code === 0) {
      // 如果有数据说明今日已打卡，如果为null说明未打卡
      todayChecked.value = !!todayPunchResponse.data
    }
  } catch (error) {
    console.error('检查打卡状态失败:', error)
  }
}

// 更新活动列表数据
const updateActivityList = (tab: string, punchList: PunchRecordRespVO[]) => {
  console.log(`[updateActivityList] ${tab} 处理数据:`, punchList.length, '条')
  console.log(`[updateActivityList] ${tab} 第一条数据:`, punchList[0])

  const activityList = punchList.map(punch => {
    // 处理用户信息显示
    const userInfo = punch.userInfo
    const displayName = userInfo?.nickname || userInfo?.username || `用户${userInfo?.userId || 'unknown'}`
    const avatarText = displayName.charAt(0).toUpperCase()

    return {
      id: punch.id,
      userId: userInfo?.userId, // 只使用真实的用户ID，不使用punch.id作为fallback
      username: displayName,
      timeDesc: formatTimeDesc(punch.createTime || punch.updateTime || new Date().toISOString()),
      checkinDesc: `打卡第${punch.dayCount || 1}天，读了${punch.bookCount}本`,
      readingTitle: `今天读了${punch.bookCount}本书`,
      readingCount: `读了${punch.bookCount}本`,
      commentText: punch.commentText, // 用户心得
      avatarText: avatarText,
      avatarBg: '#6c5ce7',
      avatarLoadError: false, // 初始化头像加载错误状态
      isFollowed: punch.isFollowed || false, // 使用真实的关注状态
      userInfo: punch.userInfo, // 保留完整的用户信息
      books: punch.books?.map(book => ({
        id: book.id,
        title: book.title && book.title.length > 8 ? book.title.substring(0, 8) + '...' : book.title || '未知绘本',
        cover: book.cover || ''
      })) || [],
      // 详情弹窗需要的完整数据
      fullTime: punch.createTime || punch.updateTime || new Date().toISOString(),
      readingTime: 0, // 阅读时长（秒）- 暂时设为0
      dayCount: punch.dayCount || 1,
      punchDate: Array.isArray(punch.punchDate) ? punch.punchDate.join('-') : punch.punchDate,
      fullBooks: punch.books?.map(book => ({
        id: book.id,
        title: book.title || '未知绘本', // 完整标题，不截断
        cover: book.cover || '',
        bookSetTitle: book.bookSetTitle
      })) || [],
      rawData: punch // 保存原始数据，以备不时之需
    }
  })

  switch (tab) {
    case 'latest':
      latestActivityList.value = activityList
      break
    case 'follow':
      followActivityList.value = activityList
      break
    case 'mine':
      myActivityList.value = activityList
      break
  }

  console.log(`[updateActivityList] ${tab} 更新完成，活动列表长度:`, activityList.length)
  console.log(`[updateActivityList] ${tab} 当前显示列表:`, getCurrentActivityList(tab).length)
}

// 格式化时间描述 - 相对时间保留，具体日期使用 yyyy/mm/dd 格式
const formatTimeDesc = (timeStr: string): string => {
  const now = new Date()
  const time = new Date(timeStr)
  const diff = now.getTime() - time.getTime()
  const minutes = Math.floor(diff / (1000 * 60))

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`

  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}小时前`

  const days = Math.floor(hours / 24)
  if (days < 7) return `${days}天前`

  // 超过7天时，显示 yyyy/mm/dd 格式
  const year = time.getFullYear()
  const month = (time.getMonth() + 1).toString().padStart(2, '0')
  const day = time.getDate().toString().padStart(2, '0')

  return `${year}/${month}/${day}`
}

// 格式化完整时间显示
const formatFullTime = (timeStr: string): string => {
  const time = new Date(timeStr)
  const year = time.getFullYear()
  const month = (time.getMonth() + 1).toString().padStart(2, '0')
  const day = time.getDate().toString().padStart(2, '0')
  const hour = time.getHours().toString().padStart(2, '0')
  const minute = time.getMinutes().toString().padStart(2, '0')

  return `${year}年${month}月${day}日 ${hour}:${minute}`
}

// 格式化阅读时长
const formatReadingTime = (seconds: number): string => {
  if (seconds < 60) {
    return `${seconds}秒`
  } else if (seconds < 3600) {
    const minutes = Math.floor(seconds / 60)
    return `${minutes}分钟`
  } else {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    return minutes > 0 ? `${hours}小时${minutes}分钟` : `${hours}小时`
  }
}

// 显示动态详情
const showActivityDetail = (activity: any) => {
  selectedActivity.value = activity
  showDetailModal.value = true
}

// 隐藏动态详情
const hideActivityDetail = () => {
  showDetailModal.value = false
  selectedActivity.value = null
}

// 显示今日绘本弹窗
const showAllBooksModal = () => {
  showAllBooksModalVisible.value = true
}

// 隐藏今日绘本弹窗
const hideAllBooksModal = () => {
  showAllBooksModalVisible.value = false
}

// 初始化数据
const initData = async () => {
  loading.value = true
  activityLoading.value = true
  try {
    // 先加载用户信息，这是后续逻辑的基础
    await loadCurrentUser()

    // 如果用户信息加载失败（未登录），不继续加载其他数据
    if (!currentUser.value) {
      return
    }

    // 加载关注列表
    await loadFollowingList()

    // 然后并行加载其他数据
    await Promise.all([
      loadPunchStats(),
      loadTodayReading(),
      checkTodayPunchStatus(),
      loadPunchRecords(activeTab.value),
      generateRecentDays()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
  } finally {
    loading.value = false
    activityLoading.value = false
  }
}

onLoad(() => {
  initData()
})

onShow(async () => {
  // 页面显示时刷新数据
  try {
    activityLoading.value = true

    // 确保用户信息是最新的
    if (!currentUser.value) {
      await loadCurrentUser()
      // 如果用户信息加载失败（未登录），不继续刷新其他数据
      if (!currentUser.value) {
        return
      }
      await loadFollowingList()
    }

    await Promise.all([
      loadPunchStats(),
      loadTodayReading(),
      checkTodayPunchStatus(),
      loadPunchRecords(activeTab.value),
      generateRecentDays()
    ])
  } catch (error) {
    console.error('刷新数据失败:', error)
  } finally {
    activityLoading.value = false
  }
})
</script>

<style lang="scss" scoped>
// 导入公共样式变量
@import '@/styles/variables.scss';

.study-checkin-container {
  background: $bg-gradient;
  min-height: 100vh;
  padding: $container-padding;
}

/* 功能图标 - 儿童友好风格 */
.function-icons {
  display: flex;
  justify-content: space-around;
  padding: $card-padding;
  @include glass-effect;
  border-radius: $border-radius-xl;
  margin-bottom: $section-margin;
  box-shadow: $shadow-lg;

  .icon-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    transition: $transition-all;
    @include click-scale;

    .icon-wrapper {
      width: $category-icon-size;
      height: $category-icon-size;
      border-radius: $border-radius-full;
      @include center-flex;
      margin-bottom: $spacing-sm;
      box-shadow: $shadow-md;
      transition: $transition-all;

      .iconfont {
        font-size: $icon-lg;
        color: $white;
      }
    }

    .icon-label {
      font-size: $font-size-sm;
      color: $dark-gray;
      font-weight: $font-weight-medium;
      font-family: $font-family;
    }

    &:hover {
      .icon-wrapper {
        transform: scale(1.05);
        box-shadow: $shadow-lg;
      }
    }
  }
}

/* 阅读统计和打卡区域 - 儿童友好风格 */
.reading-checkin-section {
  @include card-container;

  /* 总阅读天数 */
  .total-reading {
    text-align: center;
    padding: $spacing-md;
    border-bottom: 1px solid $border-color-light;
    margin-bottom: $spacing-sm;

    .total-title {
      display: block;
      font-size: $font-size-lg;
      color: $dark-gray;
      margin-bottom: $spacing-sm;
      font-family: $font-family;
      font-weight: $font-weight-medium;
    }

    .total-days {
      font-size: $font-size-3xl;
      font-weight: $font-weight-bold;
      color: $primary-blue;
      font-family: $font-family;
      text-shadow: 0 2px 4px rgba(66, 187, 255, 0.2);
    }
  }

  /* 阅读统计 */
  .reading-stats {
    display: flex;
    justify-content: space-around;
    padding: $spacing-md $spacing-xl;
    margin-bottom: $spacing-lg;

    .stat-item {
      text-align: center;
      padding: $spacing-md;
      border-radius: $border-radius-lg;
      background: rgba(66, 187, 255, 0.05);
      transition: $transition-all;

      &:hover {
        background: rgba(66, 187, 255, 0.1);
        transform: translateY(-2px);
      }

      .stat-label {
        display: block;
        font-size: $font-size-sm;
        color: $medium-gray;
        margin-bottom: $spacing-xs;
        font-family: $font-family;
        font-weight: $font-weight-medium;
      }

      .stat-number {
        font-size: $font-size-2xl;
        font-weight: $font-weight-bold;
        color: $primary-blue;
        font-family: $font-family;
      }

      .stat-unit {
        font-size: $font-size-base;
        color: $medium-gray;
        margin-left: 2px;
        font-family: $font-family;
      }
    }
  }

  /* 绘本展示区域 - 儿童友好风格 */
  .books-display {
    padding: 1px;

    .books-grid {
      display: flex;
      justify-content: center;
      gap: $spacing-sm;
      flex-wrap: wrap;
    }

    .book-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 90px;
      transition: $transition-all;
      @include click-scale;

      &:hover {
        transform: translateY(-4px);
      }

      .book-cover {
        width: 70px;
        height: 90px;
        border-radius: $border-radius-md;
        box-shadow: $shadow-md;
        margin-bottom: $spacing-sm;
        background-color: $light-gray;
        transition: $transition-all;

        &:hover {
          box-shadow: $shadow-lg;
        }
      }

      .book-title {
        font-size: $font-size-sm;
        color: $dark-gray;
        text-align: center;
        line-height: $line-height-tight;
        max-width: 80px;
        font-family: $font-family;
        font-weight: $font-weight-medium;
        @include text-ellipsis-multiline(2);
      }
    }

    .more-books {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 90px;
      transition: $transition-all;
      @include click-scale;

      .more-icon {
        width: 70px;
        height: 90px;
        border-radius: $border-radius-md;
        background: linear-gradient(135deg, $light-gray 0%, rgba(66, 187, 255, 0.1) 100%);
        border: 2px dashed $primary-blue;
        @include center-flex;
        margin-bottom: $spacing-sm;
        transition: $transition-all;

        &:hover {
          background: linear-gradient(135deg, rgba(66, 187, 255, 0.1) 0%, rgba(66, 187, 255, 0.2) 100%);
          border-color: $sky-blue;
        }

        .more-text {
          font-size: $font-size-lg;
          color: $primary-blue;
          font-weight: $font-weight-semibold;
          font-family: $font-family;
        }
      }

      .more-title {
        font-size: $font-size-sm;
        color: $dark-gray;
        text-align: center;
        font-family: $font-family;
        font-weight: $font-weight-medium;
      }
    }
  }

  /* 打卡按钮 - 儿童友好风格 */
  .checkin-button {
    padding: $spacing-lg $spacing-xl $spacing-xl;
    @include center-flex;

    .checkin-btn {
      width: 85%;
      height: $height-xl;
      background: $blue-gradient;
      color: $white;
      border: none;
      border-radius: $border-radius-3xl;
      box-shadow: $shadow-blue;
      font-family: $font-family;
      font-size: $font-size-lg;
      font-weight: $font-weight-semibold;
      cursor: pointer;
      transition: $transition-all;
      @include center-flex;

      &.checked {
        background: $green-gradient;
        box-shadow: $shadow-green;

        &:hover {
          box-shadow: 0 6px 16px rgba(50, 205, 50, 0.4);
        }
      }

      &.disabled {
        background: linear-gradient(135deg, #cccccc 0%, #999999 100%);
        box-shadow: 0 2px 8px rgba(153, 153, 153, 0.2);
        cursor: not-allowed;

        &:hover {
          transform: none;
          box-shadow: 0 2px 8px rgba(153, 153, 153, 0.2);
        }

        &:active {
          transform: none;
        }

        .checkin-text {
          color: #666666;
          text-shadow: none;
        }
      }

      .checkin-text {
        color: $white;
        font-family: $font-family;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
      }

      &:hover:not(.disabled) {
        transform: translateY(-2px);
      }

      &:active:not(.disabled) {
        transform: translateY(0) scale(0.98);
      }
    }
  }
}

/* 打卡日历 - 儿童友好风格 */
.calendar-section {
  @include card-container;

  & {
    padding: $spacing-md;
  }

  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: $spacing-xl;

    .calendar-title {
      font-size: $font-size-xl;
      font-weight: $font-weight-semibold;
      color: $dark-gray;
      font-family: $font-family;
    }

    .calendar-nav {
      font-size: $font-size-base;
      color: $primary-blue;
      font-weight: $font-weight-medium;
      padding: $spacing-sm $spacing-md;
      background: rgba(66, 187, 255, 0.1);
      border-radius: $border-radius-lg;
      transition: $transition-all;
      font-family: $font-family;
      @include click-scale;

      &:hover {
        background: rgba(66, 187, 255, 0.2);
      }
    }
  }

  .recent-calendar {
    display: flex;
    justify-content: space-around;
    gap: $spacing-sm;
    width: 100%;

    .day-item {
      text-align: center;
      flex: 1;

      .day-name {
        display: block;
        font-size: $font-size-sm;
        color: $medium-gray;
        margin-bottom: $spacing-xs;
        font-family: $font-family;
        font-weight: $font-weight-medium;
      }

      .week-day {
        display: block;
        font-size: $font-size-xs;
        color: $medium-gray;
        margin-bottom: $spacing-sm;
        font-family: $font-family;
        font-weight: $font-weight-regular;
        text-align: center;
      }

      .day-circle {
        width: 40px;
        height: 40px;
        border-radius: $border-radius-full;
        background-color: $light-gray;
        @include center-flex;
        border: 2px solid transparent;
        transition: $transition-all;
        margin: 0 auto;

        &.checked {
          background: $green-gradient;
          box-shadow: $shadow-green;

          .day-number {
            color: $white;
          }
        }

        &.today {
          border-color: $primary-blue;

          &:not(.checked) {
            background: rgba(66, 187, 255, 0.1);

            .day-number {
              color: $primary-blue;
              font-weight: $font-weight-bold;
            }
          }

          &.checked {
            // 今天已打卡：绿色背景 + 蓝色边框
            background: $green-gradient;
            border: 2px solid $primary-blue;
            box-shadow: $shadow-green, 0 0 8px rgba(66, 187, 255, 0.5);

            .day-number {
              color: $white;
              font-weight: $font-weight-bold;
            }
          }
        }

        .day-number {
          font-size: $font-size-base;
          color: $dark-gray;
          font-weight: $font-weight-semibold;
          font-family: $font-family;
        }

        &:hover {
          transform: scale(1.05);
          box-shadow: $shadow-md;
        }
      }
    }
  }
}

/* 动态列表 - 儿童友好风格 */
.activity-section {
  @include card-container;

  .activity-tabs {
    display: flex;
    border-bottom: 1px solid $border-color-light;
    margin-bottom: $spacing-lg;

    .tab-item {
      flex: 1;
      text-align: center;
      padding: $spacing-lg 0;
      font-size: $font-size-base;
      color: $medium-gray;
      position: relative;
      font-family: $font-family;
      font-weight: $font-weight-medium;
      transition: $transition-colors;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: $spacing-xs;

      &.active {
        color: $primary-blue;
        font-weight: $font-weight-semibold;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 40px;
          height: 3px;
          background: $blue-gradient;
          border-radius: $border-radius-xs;
        }
      }

      &.loading {
        pointer-events: none; // 加载时禁用点击
      }

      &:hover:not(.active):not(.loading) {
        color: $primary-blue;
      }

      .tab-loading {
        width: 12px;
        height: 12px;
        border: 2px solid $primary-blue;
        border-top: 2px solid transparent;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      }
    }
  }

  .activity-scroll {
    height: 600px; // 固定高度，确保滚动正常工作
    width: 100%;
  }

  .activity-list {
    .activity-item {
      padding: $spacing-lg;
      border-bottom: 1px solid $border-color-light;
      border-radius: $border-radius-lg;
      margin-bottom: $spacing-md;
      background: rgba(255, 255, 255, 0.5);
      transition: $transition-all;
      cursor: pointer;
      @include click-scale;

      &:last-child {
        border-bottom: none;
        margin-bottom: 0;
      }

      &:hover {
        background: rgba(255, 255, 255, 0.8);
        transform: translateY(-2px);
        box-shadow: $shadow-md;
      }

      &:active {
        transform: translateY(0) scale(0.98);
      }

      .user-header {
        display: flex;
        align-items: flex-start;
        margin-bottom: $spacing-md;

        .user-avatar {
          width: $avatar-md;
          height: $avatar-md;
          margin-right: $spacing-md;
          border-radius: $border-radius-full;
          overflow: hidden;
          position: relative;

          .avatar-image {
            width: 100%;
            height: 100%;
            border-radius: $border-radius-full;
          }

          .avatar-text {
            width: 100%;
            height: 100%;
            border-radius: $border-radius-full;
            @include center-flex;
            color: $white;
            font-size: $font-size-lg;
            font-weight: $font-weight-bold;
            font-family: $font-family;
            box-shadow: $shadow-sm;
          }
        }

        .user-info {
          flex: 1;

          .user-name-row {
            display: flex;
            align-items: center;
            margin-bottom: $spacing-xs;

            .username {
              font-size: $font-size-md;
              color: $dark-gray;
              font-weight: $font-weight-semibold;
              margin-right: 4px;
              font-family: $font-family;
              max-width: 120px;
              @include text-ellipsis;
            }

            .time-desc {
              font-size: $font-size-sm;
              color: $medium-gray;
              margin-right: auto;
              font-family: $font-family;
            }

            .follow-btn {
              padding: $spacing-xs $spacing-md;
              background: $blue-gradient;
              color: $white;
              border: none;
              border-radius: $border-radius-lg;
              box-shadow: $shadow-blue;
              font-family: $font-family;
              font-weight: $font-weight-medium;
              font-size: $font-size-sm;
              cursor: pointer;
              transition: $transition-all;

              &:hover {
                box-shadow: $shadow-blue-lg;
              }

              &:active {
                transform: scale(0.95);
              }

              .follow-text {
                color: $white;
                font-family: $font-family;
              }
            }
          }

          .checkin-desc {
            font-size: $font-size-base;
            color: $medium-gray;
            font-family: $font-family;
          }
        }
      }

      .reading-content {
        .reading-title {
          display: block;
          font-size: $font-size-md;
          color: $dark-gray;
          font-weight: $font-weight-semibold;
          margin-bottom: $spacing-xs;
          font-family: $font-family;
        }

        .reading-count {
          display: block;
          font-size: $font-size-base;
          color: $medium-gray;
          margin-bottom: $spacing-md;
          font-family: $font-family;
        }

        /* 用户心得内容 */
        .comment-content {
          background: rgba(66, 187, 255, 0.05);
          padding: $spacing-md;
          border-radius: $border-radius-md;
          margin: $spacing-md 0;
          border-left: 3px solid $primary-blue;
          transition: $transition-all;

          &:hover {
            background: rgba(66, 187, 255, 0.08);
          }

          .comment-text {
            font-size: $font-size-base;
            color: $dark-gray;
            line-height: $line-height-relaxed;
            font-family: $font-family;
            font-weight: $font-weight-regular;
            word-break: break-word;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }

        .book-list {
          display: flex;
          gap: $spacing-md;
          overflow-x: auto;
          padding-bottom: $spacing-xs;

          .book-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            min-width: 90px;
            transition: $transition-all;
            @include click-scale;

            &:hover {
              transform: translateY(-2px);
            }

            .book-cover {
              width: 80px;
              height: 100px;
              border-radius: $border-radius-md;
              margin-bottom: $spacing-sm;
              box-shadow: $shadow-md;
              transition: $transition-all;

              &:hover {
                box-shadow: $shadow-lg;
              }
            }

            .book-title {
              font-size: $font-size-sm;
              color: $dark-gray;
              text-align: center;
              max-width: 80px;
              font-family: $font-family;
              font-weight: $font-weight-medium;
              @include text-ellipsis;
            }
          }
        }
      }
    }
  }

  /* 动态列表加载状态 */
  .activity-loading {
    .loading-item {
      display: flex;
      align-items: flex-start;
      padding: $spacing-lg;
      margin-bottom: $spacing-md;
      background: rgba(255, 255, 255, 0.5);
      border-radius: $border-radius-lg;

      .loading-avatar {
        width: $avatar-md;
        height: $avatar-md;
        border-radius: $border-radius-full;
        background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
        background-size: 200% 100%;
        animation: shimmer 1.5s infinite;
        margin-right: $spacing-md;
      }

      .loading-content {
        flex: 1;

        .loading-line {
          height: 16px;
          border-radius: $border-radius-sm;
          background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
          background-size: 200% 100%;
          animation: shimmer 1.5s infinite;
          margin-bottom: $spacing-sm;

          &.short {
            width: 30%;
          }

          &.medium {
            width: 60%;
          }

          &.long {
            width: 80%;
          }

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }

  /* 空状态 */
  .empty-state {
    text-align: center;
    padding: $spacing-3xl;

    .empty-text {
      font-size: $font-size-base;
      color: $medium-gray;
      font-family: $font-family;
    }
  }
}

/* 加载动画 */
@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 动态详情弹窗样式 */
.detail-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(10px);
  z-index: 9999;
  @include center-flex;
  animation: fadeIn 0.3s ease-out;
}

.detail-modal-content {
  width: 90%;
  max-width: 500px;
  max-height: 85vh;
  padding-top: 10px;
  background: $white;
  border-radius: $border-radius-xl;
  box-shadow: $shadow-2xl;
  position: relative;
  overflow: hidden;
  animation: slideUp 0.3s ease-out;
  display: flex;
  flex-direction: column;
}

.modal-scroll-container {
  flex: 1;
  height: 100%;
  max-height: calc(80vh - 60px); // 减去关闭按钮的空间
}

.modal-close-btn {
  position: absolute;
  top: $spacing-md;
  right: $spacing-md;
  width: 32px;
  height: 32px;
  border-radius: $border-radius-full;
  background: rgba(0, 0, 0, 0.1);
  z-index: 10;
  transition: $transition-all;
  @include center-flex;
  @include click-scale;

  &:hover {
    background: rgba(0, 0, 0, 0.2);
  }
}

.modal-user-header {
  display: flex;
  align-items: center;
  padding: $spacing-2xl $spacing-2xl $spacing-md;

  .modal-user-avatar {
    width: $avatar-lg;
    height: $avatar-lg;
    margin-right: $spacing-md;
    border-radius: $border-radius-full;
    overflow: hidden;
    position: relative;

    .avatar-image {
      width: 100%;
      height: 100%;
      border-radius: $border-radius-full;
    }

    .avatar-text {
      width: 100%;
      height: 100%;
      border-radius: $border-radius-full;
      @include center-flex;
      color: $white;
      font-size: $font-size-xl;
      font-weight: $font-weight-bold;
      font-family: $font-family;
      box-shadow: $shadow-md;
    }
  }

  .modal-user-info {
    flex: 1;

    .modal-username {
      display: block;
      font-size: $font-size-lg;
      color: $dark-gray;
      font-weight: $font-weight-bold;
      margin-bottom: $spacing-xs;
      font-family: $font-family;
    }

    .modal-time {
      display: block;
      font-size: 6px;
      color: $medium-gray;
      margin-bottom: $spacing-xs;
      font-family: $font-family;
    }

    .modal-day-count {
      display: block;
      font-size: $font-size-sm;
      color: $primary-blue;
      font-weight: $font-weight-semibold;
      font-family: $font-family;
    }
  }

  .modal-header-follow-btn {
    padding: $spacing-md $spacing-md;
    background: $blue-gradient;
    color: $white;
    border-radius: $border-radius-lg;
    box-shadow: $shadow-blue;
    transition: $transition-all;
    @include center-flex;
    @include click-scale;

    &:hover {
      box-shadow: $shadow-blue-lg;
    }

    .header-follow-text {
      font-size: $font-size-xs;
      color: $white;
      font-weight: $font-weight-semibold;
      font-family: $font-family;
      text-align: center;
      line-height: 1;
    }
  }
}

.modal-divider {
  height: 1px;
  background: $border-color-light;
  margin: 0 $spacing-xl;
}

.modal-reading-stats {
  padding: $spacing-lg $spacing-xl;

  .stats-header {
    display: flex;
    align-items: center;
    margin-bottom: $spacing-md;

    .stats-icon {
      font-size: $font-size-lg;
      margin-right: $spacing-sm;
    }

    .stats-title {
      font-size: $font-size-lg;
      color: $dark-gray;
      font-weight: $font-weight-semibold;
      font-family: $font-family;
    }
  }

  .stats-content {
    font-size: $font-size-base;
    color: $medium-gray;
    line-height: $line-height-relaxed;
    font-family: $font-family;
  }
}

.modal-comment-section {
  padding: $spacing-lg $spacing-xl;
  width: 100%;
  box-sizing: border-box;

  .comment-header {
    display: flex;
    align-items: center;
    margin-bottom: $spacing-md;

    .comment-icon {
      font-size: $font-size-lg;
      margin-right: $spacing-sm;
    }

    .comment-title {
      font-size: $font-size-lg;
      color: $dark-gray;
      font-weight: $font-weight-semibold;
      font-family: $font-family;
    }
  }

  .modal-comment-text {
    font-size: $font-size-base;
    color: $dark-gray;
    line-height: $line-height-relaxed;
    font-family: $font-family;
    background: rgba(66, 187, 255, 0.05);
    padding: $spacing-md;
    border-radius: $border-radius-md;
    border-left: 3px solid $primary-blue;
    word-break: break-word;
    word-wrap: break-word;
    white-space: pre-wrap;
    width: 100%;
    box-sizing: border-box;
    min-height: 60px;
    height: auto;
    max-height: none;
    overflow-wrap: break-word;
    display: block;
  }
}

.modal-books-section {
  padding: $spacing-lg $spacing-xl;

  .books-header {
    display: flex;
    align-items: center;
    margin-bottom: $spacing-lg;

    .books-icon {
      font-size: $font-size-lg;
      margin-right: $spacing-sm;
    }

    .books-title {
      font-size: $font-size-lg;
      color: $dark-gray;
      font-weight: $font-weight-semibold;
      font-family: $font-family;
    }
  }

  .modal-books-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: $spacing-md;
  }

  .modal-book-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;

    .modal-book-cover {
      width: 70px;
      height: 90px;
      border-radius: $border-radius-md;
      margin-bottom: $spacing-sm;
      box-shadow: $shadow-md;
      transition: $transition-all;

      &:hover {
        box-shadow: $shadow-lg;
        transform: translateY(-2px);
      }
    }

    .modal-book-title {
      font-size: $font-size-sm;
      color: $dark-gray;
      font-weight: $font-weight-medium;
      margin-bottom: $spacing-xs;
      font-family: $font-family;
      line-height: $line-height-tight;
      word-break: break-word;
    }

    .modal-book-set {
      font-size: $font-size-xs;
      color: $medium-gray;
      font-family: $font-family;
    }
  }
}



/* 弹窗动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(50px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 今日绘本弹窗特有样式 */
.modal-books-header {
  padding: $spacing-lg 0;
  text-align: center;

  .books-header {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: $spacing-sm;

    .books-icon {
      font-size: $font-size-xl;
      margin-right: $spacing-sm;
    }

    .books-title {
      font-size: $font-size-xl;
      color: $dark-gray;
      font-weight: $font-weight-semibold;
      font-family: $font-family;
    }
  }

  .books-count {
    font-size: $font-size-base;
    color: $medium-gray;
    font-family: $font-family;
  }
}

/* 加载更多指示器样式 */
.load-more-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: $spacing-lg;

  .loading-spinner {
    width: 16px;
    height: 16px;
    border: 2px solid $border-color-light;
    border-top: 2px solid $primary-blue;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-right: $spacing-sm;
  }

  .loading-text {
    font-size: $font-size-sm;
    color: $medium-gray;
  }
}

.no-more-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: $spacing-lg;

  .no-more-text {
    font-size: $font-size-sm;
    color: $light-gray;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

</style>
